from PySide6.QtCore import Signal, QObject, Slot, Qt
import webbrowser
# from codes.ctypes_VirtualKeys import KeyboardSimulator
import time
import threading
#import ctypes
# from codes.ctypes_VirtualKeys import KeyboardSimulator

import pyautogui

class ScreenDataProcessor(QObject):
    signal_LogIn = Signal(str)
    #Instance1 = AltTabSimulator()
    def __init__(self, parent=None):
        super().__init__(parent)
        # self.input_simulator = SerialInputSimulator()  # 创建SerialInputSimulator实例

        self.signal_LogIn.connect(self.loginOshwhub)
        # self.inputsimulator =KeyboardSimulator()


    def simulate_hotkey_bystr(self,shortcut):
        # 将快捷键字符串拆分为键名列表

        keys_upper = shortcut.lower()
        keys = keys_upper.split('+')

        # 验证每个键是否有效
        valid_keys = pyautogui.KEYBOARD_KEYS
        for key in keys:
            if key not in valid_keys:
                raise ValueError(f"Invalid key: {key}")

        # 模拟快捷键
        try:
            pyautogui.hotkey(*keys)
            print(f"hotkey '{shortcut}'")
        except Exception as e:
            print(f"Error simulating hotkey '{shortcut}': {e}")
    def simulate_hotkey_bystr2(self,shortcut):
        # 将快捷键字符串拆分为键名列表
        if '+' in shortcut:
            operation = 'simultaneous'
            keys = shortcut.lower().split('+')
        elif '>' in shortcut:
            operation = 'sequential'
            keys = shortcut.lower().split('>')
        else:
            operation = 'simultaneous'
            keys = shortcut.lower().split('+')  # 默认为同时按下

        # 验证每个键是否有效
        valid_keys = pyautogui.KEYBOARD_KEYS
        for key in keys:
            if key not in valid_keys:
                raise ValueError(f"Invalid key: {key}")

        # 根据操作符决定模拟方式
        if operation == 'simultaneous':
            # 同时按下所有键
            try:
                pyautogui.hotkey(*keys)
                print(f"Simulated simultaneous hotkey '{shortcut}'")
            except Exception as e:
                print(f"Error simulating simultaneous hotkey '{shortcut}': {e}")
        elif operation == 'sequential':
            # 依次按下所有键
            try:
                for key in keys:
                    pyautogui.press(key)
                    time.sleep(0.2)  # 可以根据需要调整延迟时间
                print(f"Simulated sequential hotkey '{shortcut}'")
            except Exception as e:
                print(f"Error simulating sequential hotkey '{shortcut}': {e}")

    def OpenFile_Handler(self, file_path):
        """处理打开文件事件"""
        print("-打开文件-")
        # 假设这里使用操作系统默认程序打开文件
        #os.startfile(file_path)  # Windows平台
        # 或者使用subprocess或其他方式根据平台进行调整

    def OpenWeb_Handler(self, url):
        """处理打开网页事件"""
        print("-登陆网址：-")
        self.signal_LogIn.emit(url)

    def PCcontrol_Handler(self):
        """处理PC控制事件"""
        print("-PC控制-")
        # 这里可以添加PC控制的具体逻辑
    def KeyboardInput_Handler(self, inputstr):
        """处理键盘输入事件"""
        print("-键盘输入-")
        #self.simulate_hotkey_bystr(inputstr)
        self.simulate_hotkey_bystr2(inputstr)
    def execute_statemachine(self, funcstr,paramstr): # funcstr,paramstr 都是str，这是暂时的操作，因为paramstr还有两个暂时不用
        if funcstr == 'keyboard':
            # 打印 row_data 以查看其内容
            self.KeyboardInput_Handler(paramstr)
        elif funcstr == 'url':
            print("-登陆网址：-")
            self.OpenWeb_Handler(paramstr)

        elif funcstr == 'openfile':
            print("-打开文件-")
        else:
            print("-未找到-")

    @Slot(str)
    def loginOshwhub(self,url):
        #print("--slot recieve:")
        print(url)
        webbrowser.open(url)

def testmain():
    DataProcessorInstance = ScreenDataProcessor()
    # 示例快捷键
    shortcuts = ['ctrl+c', 'ctrl+v',]

    # 等待用户准备好
    print("Script will start in 5 seconds. Make sure the target window is active.")
    time.sleep(5)
    print("--ready--")
    # 模拟每个快捷键
    DataProcessorInstance.simulate_hotkey('ctrl+c')
    time.sleep(2.5)
    DataProcessorInstance.simulate_hotkey('ctrl+v')
    print("Simulation complete.")

if __name__ == '__main__':
    testmain()